/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.shiro.realm;

import com.bifrost.entity.Permission;
import com.bifrost.entity.Role;
import com.bifrost.entity.User;
import com.bifrost.repository.AdminUserRepository;
import com.bifrost.repository.RoleRepository;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author joewee
 * @version 1.0.0
 * @Date 2018/4/4 15:56
 */
@Component
public class AdminUserRealm extends AuthorizingRealm {

    AdminUserRepository adminUserRepository ;
    @Autowired
    ApplicationContext context;
    @Autowired
    RoleRepository roleRepository;

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();

        List<String> permissionList = new ArrayList<>();
        List<String> roleList = new ArrayList<>();

        Set<Role> roleSet =  roleRepository.findAllByUsersIs(user);

        if (CollectionUtils.isNotEmpty(roleSet)) {
            for (Role role : roleSet) {
                roleList.add(role.getRoleName());
                Set<Permission> permissionSet = role.getPermissions();
                if (CollectionUtils.isNotEmpty(permissionSet)) {
                    for (Permission permission : permissionSet) {
                        if (StringUtils.isNotBlank(permission.getIdentifier())){//目录和菜单没有权限标识，所以排除这两种情况
                            for (String identifier : permission.getIdentifier().split(",")) {
                                permissionList.add(identifier);
                            }
                        }
                    }
                }
            }
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roleList);
        info.addStringPermissions(permissionList);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        getAdminRepository();
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        //根据username用户数据
        User user = adminUserRepository.findFirstByAdminName(username);
        //账号不存在
        if (user == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }
        //账号锁定
        if (!Boolean.TRUE.equals(user.isActive())) {
            throw new LockedAccountException("账号未激活,请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getAdminPassword(), getName());
        return info;
    }

    void getAdminRepository() {
        if(adminUserRepository==null){
            adminUserRepository = context.getBean(AdminUserRepository.class);
        }
    }

}
